<template>
  <!-- 新增或修改岗位 -->
  <el-dialog :visible.sync="visible"
             v-if="visible"
             @close="dialogClose"
             :close-on-click-modal="false"
             :title="dialogStatus==='create'?'新增岗位':'修改岗位'"
             width="30%">
    <el-form :model="editJobForm"
             :rules="editJobFormRules"
             ref="editJobForm"
             label-width="90px">
      <el-form-item label="岗位名称"
                    prop="job_name">
        <el-input v-model="editJobForm.job_name"
                  autocomplete="off"
                  placeholder="请输入岗位名称"
                  style="width:100%!important"></el-input>
      </el-form-item>
      <el-form-item label="岗位分类">
        <el-select v-model="editJobForm.job_cate">
          <el-option v-for="(item,ind) in jobCateArr"
                     :key="ind"
                     :label="item.name"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注"
                    class="add_tips">
        <el-input v-model="editJobForm.input_remark"
                  autocomplete="off"
                  style="width:100%!important"></el-input>
      </el-form-item>
      <el-form-item label="业务领域"
                    class="add_tips">
        <el-select v-model="editJobForm.business_field"
                   style="display:block!important"
                   @change="changBusiness"
                   multiple
                   placeholder="请选择业务领域">
          <el-option v-for="item in businessArea"
                     :key="item.value"
                     :label="item.name"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="管理职能"
                    class="add_tips">
        <el-select v-model="editJobForm.manage_function"
                   style="display:block!important"
                   @change="changManage"
                   multiple
                   placeholder="请选择管理职能">
          <el-option v-for="item in manageFunction"
                     :key="item.value"
                     :label="item.name"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div style="text-align:center;">
      <el-button @click="dialogClose"
                 id="back-style">返 回</el-button>
      <el-button @click="editJob"
                 type="primary"
                 id="save-style">保 存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { organizationApi } from '@/services/CompanySetting'
import { standardCodeApi } from '@/services/StandardCode'
export default {
  data () {
    return {
      businessArea: [], //业务领域
      manageFunction: [], //管理职能
      visible: false,
      jobCateArr: [],//岗位分类
      editJobForm: {
        job_cate: '',//岗位分类
        job_name: '',
        input_remark: '',
        business_field: '', //业务领域
        manage_function: '', //管理职能
      },
      editJobFormRules: {
        job_name: [
          { required: true, message: '请输入岗位名称', trigger: 'blur' }
        ],
        business_field: [
          { required: true, message: '请选择业务领域类别', trigger: ['blur', 'change'] }
        ],
        manage_function: [
          { required: true, message: '请选择管理职能类别', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  props: {
    dialogVisible: Boolean,
    dialogForm: Object,
    dialogStatus: String,
    callback: Function
  },
  watch: {
    dialogVisible: {
      handler (newval, oldval) {
        this.visible = newval
      },
      deep: true
    },
    dialogForm: {
      handler (newval, oldval) {
        this.editJobForm = Object.assign(this.editJobForm, JSON.parse(JSON.stringify(newval)))
        this.editJobForm.input_node_type = '3'
      },
      deep: true
    },
    dialogStatus (newval, oldval) {
      if (newval === 'update') {
        this.editJobForm.job_name = this.editJobForm.name
        this.editJobForm.input_remark = this.editJobForm.remark
        this.detailjob()
      } else if (newval === 'create') {
        this.editJobForm.job_name = ''
        this.editJobForm.input_remark = ''
        this.editJobForm.business_field = [] //业务领域
        this.editJobForm.manage_function = [] //管理职能
      }
    }
  },
  methods: {    // 岗位分类标准码
    getJobCateCode () {
      this.jobCateArr = [];//岗位分类
      return standardCodeApi.getConsoleStandardCode({//getStandardCodeData
        params: {
          code_type: 'consoleJobCate',//岗位分类
          is_page: 0
        }
      }).then((res) => {
        if (res.code == 0) {
          let list = res.data.list || [];
          this.jobCateArr = list;
          window.localStorage.setItem('consoleJobCateUnique', JSON.stringify(list));
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 获取业务领域标准码
    getbusinessCode () {
      this.businessArea = [];
      return standardCodeApi.getConsoleStandardCode({//getStandardCodeData
        params: {
          code_type: 'businessField',
          is_page: 0
        }
      }).then((res) => {
        if (res.code == 0) {
          let list = res.data.list || [];
          this.businessArea = list;
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 获取管理职能标准码
    getmanageCode () {
      this.manageFunction = [];
      return standardCodeApi.getConsoleStandardCode({//getStandardCodeData
        params: {
          code_type: 'manageFunction',
          is_page: 0
        }
      }).then((res) => {
        if (res.code == 0) {
          let list = res.data.list || [];
          this.manageFunction = list;
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    //管理职能选择框
    changManage (val) {
      this.editJobForm.manage_function = val
    },
    //业务领域选择框
    changBusiness (val) {
      this.editJobForm.business_field = val
    },
    dialogClose () {
      this.$refs.editJobForm.resetFields()
      this.$emit('update:dialogVisible', false)
      this.$emit('update:dialogStatus', '')
    },
    editJob () {
      this.$refs.editJobForm.validate((valid) => {
        if (valid) {
          if (this.dialogStatus === 'create') {//新增
            this.createJob()
          } else if (this.dialogStatus === 'update') {//修改
            this.updateJob()
          }
        }
      })
    },
    createJob () {//新增
      this.$refs.editJobForm.validate((valid) => {
        if (valid) {
          this.editJobForm.business_field = this.editJobForm.business_field.join(',')
          this.editJobForm.manage_function = this.editJobForm.manage_function.join(',')
          this.$set(this.editJobForm, 'dept_id', this.editJobForm.id);//部门主键值
          this.$set(this.editJobForm, 'is_admin', 0);//是否部门主管（0：否，1：是）
          this.$set(this.editJobForm, 'input_name', this.editJobForm.job_name);//岗位名称          
          delete this.editJobForm.children_list
          delete this.editJobForm.children
          organizationApi.createDept({//旧的新增岗位接口 createOrg
            data: this.editJobForm
          }).then(res => {
            if (res.code === 0) {
              this.$message.success('新增岗位成功')
              this.dialogClose()
              this.$emit('callback', 'success')
            }
          })
        }
      })
    },
    updateJob () {
      this.editJobForm.job_id = this.editJobForm.id
      this.editJobForm.dept_id = this.editJobForm.p_id
      this.editJobForm.job_name = this.editJobForm.job_name
      this.editJobForm.remark = this.editJobForm.input_remark
      this.editJobForm.business_field = this.editJobForm.business_field.join(',')
      this.editJobForm.manage_function = this.editJobForm.manage_function.join(',')
      delete this.editJobForm.children_list
      delete this.editJobForm.children
      organizationApi.updateJob({
        data: this.editJobForm
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('修改岗位成功')
          this.dialogClose()
          this.$emit('callback', 'success')
        }
      })
    },
    getBusinessField (arr) {//业务领域
      let newArr = [];
      if (arr.length == 1 && arr[0] == '') {
        newArr = []
      } else {
        newArr = arr
      };
      return newArr;
    },
    getManageFunc (arr) {//职能
      let newArr = [];
      if (arr.length == 1 && arr[0] == '') {
        newArr = []
      } else {
        newArr = arr
      };
      return newArr;
    },
    //修改-岗位内容
    detailjob () {
      organizationApi.detailJob({
        params: {
          job_id: this.editJobForm.id,
          // show_object: 0,
          // show_app: 0
        }
      }).then(res => {
        let businessField = res.data.business_field;//业务领域
        let manageFunc = res.data.manage_function;//职能
        this.editJobForm.business_field = this.getBusinessField(businessField);//业务范围
        this.editJobForm.manage_function = this.getManageFunc(manageFunc);//职能
      }, err => {
        console.log(err);
      })
    },
  },
  async created () {
    let consoleJobCateUnique = window.localStorage.getItem('consoleJobCateUnique');//岗位分类
    if (consoleJobCateUnique) {
      this.jobCateArr = JSON.parse(consoleJobCateUnique);//岗位分类
    } else {
      await this.getJobCateCode();//岗位分类标准码
    }
    await this.getbusinessCode()
    await this.getmanageCode()
  },
  mounted () {
  }
}
</script>
<style scoped lang='scss'>
</style>
